import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/home',
      components: {
        default: () => import('@/views/Home.vue'),
        footer: () => import('@/components/Footer.vue')
      }
    },
    {
      path: '/',
      redirect: "/home"
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/Login/index.vue')
    },
    {
      // 个人中心
      path: '/center',
      name: 'center',
      component: () => import('@/views/Center/index.vue'),
       // 动态权限控制
       meta:{requiresAuth:true}

    },
    {
      // 购物车
      path: '/cart',
      name: 'cart',
      components:{
      default: () => import('@/views/Cart/Cart.vue'),
      // footer: () => import('@/components/Footer.vue')
      },
      // 动态权限控制
      meta:{requiresAuth:true}

    },
    {
      // 地址
      path: '/address',
      name: 'address',
      component: () => import('@/views/Address/Address.vue'),
      // 动态权限控制
      meta:{requiresAuth:true}
    },
    {
      // 商品详情页面
        // 另外一种传参方式
      path: '/detail/:proid',
      name: 'detail',
      component: () => import('@/views/Detail/Detail.vue'),
    },
    {
      // 订单页面
      path: '/order',
      name: 'order',
      component: () => import('@/views/Order/Order.vue'),
      meta:{requiresAuth:true}
    },
    {
      // 注册路由
      path: '/register',
      name: 'register',
      component: () => import('@/views/Register/Register.vue'),
      // 注册子路由
      children: [
        {
          path: '/register/step1',
          component: () => import("@/views/Register/RegSep1.vue")
        },
        {
          path: '/register/step2',
          component: () => import("@/views/Register/RegSep2.vue")
        },
        {
          path: '/register/step3',
          component: () => import("@/views/Register/RegSep3.vue")
        },
        {
          path:'/register',
          redirect:'/register/step1'
        }
      ]

    },
    {
      // 搜索页面
      path: '/search',
      name: 'search',
      component: () => import('@/views/Search/Search.vue')
    },

    {
      // 404页面
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import("@/views/NotFound.vue")
    }

  ]
})
/* 全局前置导航守卫实现路由的权限控制 */
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth) {
    if (localStorage.getItem("token") && localStorage.getItem("userid")) {
      //登录过,放行
      next();
    } else {
      //没有登录过,强制跳转登录页面
      next("/login")
    }
  } else {
    next();
  }
})

export default router
